package AtomicInteger_9;

import java.util.concurrent.atomic.AtomicInteger;
public class 比较并交换CAS_账户余额更新 {
    private AtomicInteger balance = new AtomicInteger(1000);

    public static void main(String[] args) {
        final 比较并交换CAS_账户余额更新 account = new 比较并交换CAS_账户余额更新();
        final int THREAD_COUNT = 15;

        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        int amount = 100;
                        Thread.sleep((long)(Math.random() * 50)); // 模拟处理时间

                        // 使用CAS更新余额
                        while (true) {
                            int current = account.balance.get();
                            int newValue = current - amount;
                            if (account.balance.compareAndSet(current, newValue)) {
                                System.out.println(Thread.currentThread().getName() +
                                                           " 成功扣款: " + amount + "，余额: " + newValue);
                                break;
                            } else {
                                System.out.println(Thread.currentThread().getName() +
                                                           " 扣款冲突，重试...");
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "扣款线程-" + i).start();
        }

        // 等待所有线程完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终余额: " + account.balance.get());
    }
}